<template>
	<div>
		<div class="container">
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="current=1;loading=true;initData()">
					<a-row>
						<a-col style="padding: 0 5px;" :span="4">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 0 5px;" :span="4">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 0 5px;" :span="4">
							<a-form-item label="选择供应商名称" name="supplier_id">
								<a-select v-model:value="searchState.supplier_id" :show-search="true" placeholder="请选择供应商" :options="userlist" option-filter-prop="label"></a-select>
							</a-form-item>
						</a-col>
						<flow-query-button @change="changeflowStatus"></flow-query-button>
						<a-col style="padding: 0 5px;" :span="4">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>

									<a-button v-permission="245" type="primary" danger @click="router.push('contract/createLX')">
										<plus-outlined />创建零星用工合同
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="contractSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="247" type="link" @click="showContract(record)">
									<right-outlined />查看
								</a-button>
								<template v-if="![0,1,2].includes(record.workflow_status)">
									<a-button v-permission="246" type="link" @click="editContract(record)">
										<edit-outlined />修改
									</a-button>
									<a-button v-permission="248" type="link" style="color:#ff7875" @click="deleteContract(record.id)">
										<delete-outlined />删除
									</a-button>
								</template>
							</a-space>
						</template>
						<template v-else-if="column.key === 'workflow_status'">
							<div>
								<a-workflow type="status" module="contractlx" :status="record.workflow_status" />
							</div>
						</template>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup lang="jsx">
import { reactive, ref, computed, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";

const { proxy } = getCurrentInstance();
import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, RightOutlined } from "@ant-design/icons-vue";

import { post } from "../utils";

import { usePagination } from "vue-request";
import { AWorkflow } from "@/components/index.js";

const searchRef = ref();
const searchState = reactive({});
const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 50,
		align: "left",
		fixed: "left"
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		width: 120,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return text?.name;
		}
	},
	{
		title: "合同名称",
		dataIndex: "name",
		sorter: false,
		width: 220,
		ellipsis: true,
		fixed: "left"
	},
	{
		title: "合同编号",
		dataIndex: "code",
		sorter: false,
		width: 220,
		ellipsis: true
	},
	{
		title: "供应商",
		dataIndex: "supplier",
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text?.company_name || text?.fullname || text?.username;
		}
	},
	{
		title: "合同金额",
		dataIndex: "amount",
		sorter: false,
		width: 100,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return `￥${text}`;
		}
	},
	{
		title: "附件",
		dataIndex: "file_path",
		sorter: false,
		width: 80,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return (text && text !== '[]') ? <a-button href={text.indexOf('{') > -1 ? JSON.parse(text)[0].url : text} target="_blank">下载</a-button> : "未上传";
		}
	},
	{
		title: "创建人",
		dataIndex: "opr_user",
		sorter: false,
		width: 80,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text.fullname || text.username;
		}
	},
	{
		title: "签订时间",
		dataIndex: "sign_time",
		width: 100,
		align: "center"
	},
	{
		title: "创建时间",
		dataIndex: "create_time",
		width: 100,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	/**
   {
   title: "最后更新时间",
   dataIndex: "update_time",
   width: 150,
   align: "center",
   customRender: ({ text, record, index, column }) => {
   return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
   }
   }, */
	{
		title: "状态",
		//dataIndex: "status",
		key: "workflow_status",
		sorter: false,
		width: 70,
		ellipsis: true
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 150,
		align: "center"
	}
];
const projectOptions = ref([]);
const companyOptions = ref([]);
const userlist = ref([]); // 供应商列表
const oprlist = ref([]); // 创建人列表
const route = useRoute();
const router = useRouter();
const query = route.query;
if (query) {
	if (query.type) searchState.type = parseInt(query.type);
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	router.replace({ query: {}})
}
const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}

post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24]),
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("user", { is_supplier: 1, page_size: 1000 }).then(({ data }) => {
	userlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.company_name || d.mobile
		};
	});
});
post("user", { page_size: 1000 }).then(({ data }) => {
	oprlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.fullname || d.username
		};
	});
});
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const itemFlowId = ref({});
const itemDepartments2 = ref({});
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
})
const changeFlowStatusData2 = (e) => {
	if (e.act === "flowInfoData") {
		var depts = e.data.flowType.departments;
		itemDepartments2.value = {
			...itemDepartments2.value,
			[e.data.item_id]: depts,
		};
		itemFlowId.value = { ...itemFlowId.value, [e.data.item_id]: e.data.id };
	}
};
const changeflowStatus = (e) => {
	if (e && searchState) {
		searchState.ids = e.ids;
		if (searchState.ids) {
			initData();
		}
	}
};
const { data, loading, run, current, pageSize, total } = usePagination(async params => {
	const search = { type: 5 };
	if (searchState.company_id) {
		if (!projectOptions.value.length) await getProjects();
		search.project_ids = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		}).map(item => item.value).join(',');
		if (!search.project_ids) {
			return [];
		}
	}
	return post("contract", { ...params, ...searchState, ...search })
}, {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

const contractSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};

if (query) {
	if (query.type) searchState.type = parseInt(query.type);
	if (query.material_type) searchState.material_type = parseInt(query.material_type);
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.supplier_id) searchState.supplier_id = parseInt(query.supplier_id);
	// router.replace({ query: {}})
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const showContract = ({ id }) => {
	router.push(`contract/infolx/${id}`);
};
const editContract = ({ id }) => {
	router.push(`contract/editlx/${id}`);
};
const deleteContract = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的合同吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("contract/delete", { id }).then(() => {
				proxy.$message.success("合同删除成功");
				initData();
			});
		}
	});
};
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;
}
</style>
